<template>
  <div class="upload">
    <el-upload
      ref="uploadRef"
      :disabled="disabled"
      :multiple="multiFile"
      action=""
      drag
      :auto-upload="false"
      :file-list="files"
      :http-request="uploadFile"
      :on-change="changeFileLength"
      :on-success="handleFileSuccess"
      :on-preview="handleFilePreview"
      :on-remove="handleFileRemove"
      :limit="limit"
      :on-exceed="handleFileExceed"
      :accept="accept"
    >
      <div class="el-upload__text">
        <IconifyIconOffline :icon="UploadIcon" width="26" class="m-auto mb-2" />
        可点击或拖拽上传
      </div>
      <template v-slot:tip>
        <div class="el-upload__tip">{{ tip }}</div>
      </template>
    </el-upload>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, watch } from "vue";

defineOptions({
  name: "ReUpload"
});
import UploadIcon from "@iconify-icons/ri/upload-2-line";
import useUploadHook from "./utils/hook";
import type { UploadProps } from "@/components/ReUpload/utils/types";

const props = withDefaults(defineProps<UploadProps>(), {
  multiFile: true,
  fileList: null,
  businessId: null,
  tableName: "",
  filePath: "",
  fileSize: 1024 * 1024 * 1024,
  limit: 5,
  disabled: false,
  tip: "上传文件大小不超过1GB",
  accept: ".jpg,.jpeg,.png,.gif,.docx,.xlsx,.xls,.pdf"
});

const {
  files,
  multiFile,
  limit,
  disabled,
  tip,
  accept,
  uploadRef,
  uploadFile,
  handleFileSuccess,
  handleFilePreview,
  handleFileRemove,
  handleFileExceed,
  changeFileLength,
  getFiles,
  upload
} = useUploadHook(props);

// 传给父组件
let emit = defineEmits(["update:fileList"]);
// 监听数组变化
watch(files, (newVal, oldVal) => {
  console.log("数组发生了变化", newVal, oldVal);
  // 在这里执行你希望在数组变化时运行的逻辑
  emit("update:fileList", newVal);
});

onMounted(async () => {
  // 获取文件列表
  await getFiles();
});

defineExpose({
  upload
});
</script>

<style lang="scss" scoped>
.upload {
  width: 100%;
}
</style>
